# -*- encoding: utf-8 -*-
# dms2002 parser
# http://194.19.56.15/ojournal/data/04092007.htm
############################################################################
#    Copyright (C) 2007 by Håvard Gulldahl                                 #
#    havard@gulldahl.no                                                    #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

import logging, re, string
from datetime import datetime
from time import strptime
import BeautifulSoup
import jeje.parser

class parser(jeje.parser.ejeje_parser):
    def parse_enkeltjournal(self, suppe, uri):
        logging.info('starter dms2002-parser')
        try:
            if suppe.body.string.strip() == u'Ingen journal er publisert for denne datoen.':
                logging.info(u'Ingen journal er publisert for denne datoen.')
                return []
        except AttributeError: pass
        d = suppe.find(text=re.compile('Periode:'))
        dato = d[len('Periode: '):]
        #dato = suppe.find('h2', 'subheadline').string[len('POSTJOURNAL-'):]
        logging.debug('fant dato %s', dato)
        self.sett_info(dato)
        logging.debug('finner tittelposter i suppa')
        RE_BODY_DIV = re.compile('font-size:10pt')
        _poster = suppe.findAll('div', attrs={'style':RE_BODY_DIV})
        logging.debug('fant %d titler', len(_poster)/26)
        j = 0
        postnr = 0
        while j < len(_poster):
            print j
            _refnr = _poster[j].next.string
            j += 1
            _retning = _poster[j].next.string
            j += 2
            _dokdato = _poster[j].next.string
            j += 2
            _jourdato = _poster[j].next.string
            j += 2
            _internavd = _poster[j].next.string
            j += 4
            _tilgkode = _poster[j].next.string
            j += 2
            _paragraf = _poster[j].next.string
            j += 1
            _avsendere = []
            _mottakere = []
            while _poster[j].next.string.strip() != u'Mottaker:':
                _avsendere.append(_poster[j].next.string.strip())
                j +=1
            j += 1
            while _poster[j].next.string.strip() != u'Sak:':
                _mottakere.append(_poster[j].next.string.strip())
                j +=1
            j += 1
            _sak = self.trekk_sammen_streng(_poster[j].next)
            j += 2
            _tittel = self.trekk_sammen_streng(_poster[j].next)
            j += 2
            _saksansv = _poster[j].next.string
            j += 2
            _saksbeh = _poster[j].next.string
            j += 1
            postnr += 1
            
            
            #_refnr, _retning, __dokdato, _dokdato, __jourdato, _jourdato, \
            #__internavd, _internavd, _tom1, _tom2, __tilgkode, _tilgkode, \
            #__paragraf, _paragraf, __avsender, _avsender, \
            #__mottaker, _mottaker, __sak, _sak, __tittel, _tittel, \
            #__saksansv, _saksansv, __saksbeh, \
            #_saksbeh = [a.next.string for a in alleposter[i:i+26]]

            logging.debug('arbeider med post #%d: %s', postnr, _tittel)

            post = self.legg_til_post()
            post.sett_tittel(unicode(_tittel))
            _arkivsaksnr, _dokumentnr = _refnr.split('-')
            logging.debug('arkivsaksnr: %s', _arkivsaksnr)
            post.sett_arkivsaksnr(unicode(_arkivsaksnr))
            post.sett_dokumentnr(unicode(_dokumentnr))
            post.sett_retning(unicode(_retning))
            if _retning == 'U':
                post.sett_adressat(string.join(_mottakere, ', '))
            else:
                post.sett_adressat(string.join(_avsendere, ', '))
            try:
                _beh_org, _beh_navn = _saksbeh.split('/')
            except: 
                _beh_org = _saksbeh
                _beh_navn = u'Ukjent'
            person = post.sett_saksbehandler(unicode(_beh_navn).strip())
            avdeling = person.sett_organisasjon(unicode(_beh_org).strip())
            avdeling.type = u'avdeling'
            avdeling.moder_id = post.sett_postjournal.organisasjon_id
            post.sett_dokumentdato(datetime(*strptime(unicode(_dokdato), '%d%m%Y')[0:6]))
            post.sett_arkivdato(datetime(*strptime(unicode(_jourdato), '%d%m%Y')[0:6]))
            if len(_paragraf.strip()):
                post.sett_offentlig(False)
                post.sett_lovreferanse(unicode(_paragraf))
            #post.sett_refnr(uri.split('&JP_ID=')[1])
            post.sett_sakskompleks(unicode(_sak))
            post.kontroller_felter()
        return self.journalposter
            
